//首先引入https和querystring模块
var https = require('https');
var qs = require('querystring');

var verCode = 123456
const apikey = '8e90adad69edfd0cea3ca0246e833f3a';
//注意这里固定格式【此处为后台设置的签名】
//var text = '【云片网】您的验证码是'+verCode;
//例子：var text = '【天天测试】感谢您的注册，您的验证码是'+verCode;

//这里我们不需要自定义模板和语音验证，国际和国内请求的短信验证是同一个url
//嫌麻烦的话这里可以直接定义为一个url
var sms_host = 'sms.yunpian.com';  //请求地址的url
send_sms_uri = '/v2/sms/single_send.json';  //请求地址的url

function post(uri,content,host,success,error){
    var options = {
        hostname: host,
        port: 443,
        path: uri,
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        }
    };
    var request = https.request(options, function (response) {
        response.setEncoding('utf8');
        response.on('data', function (chunk) {
            success && success(chunk,verCode)
        });
    });
    request.on('error', (e) => {
        console.log(e)
        error && error()
    });
    request.write(content)
    request.end();
}
//调用发送验证码，参数请求地址、apikey、手机号、自定义模板内容
//send_sms(send_sms_uri,apikey,mobile,text);
//send_sms方法
module.exports = function send_sms(mobile,success,error){
    verCode = parseInt(Math.random() * (1000000 - 100000) + 100000)
    //注意这里固定格式【此处为后台设置的签名】
    var text = '【云片网】您的验证码是'+verCode;
    var post_data = {
        'apikey': apikey,
        'mobile':mobile,
        'text':text
    };
    var content = qs.stringify(post_data);
    //把发送的数据解析为字符串发送
    post(send_sms_uri,content,sms_host,success,error);
}
